package com.aizuda.boot.modules.business.contract.controller;

import com.aizuda.boot.modules.business.contract.entity.ContractFieldEntity;
import com.aizuda.boot.modules.business.contract.entity.EmployeeTableFilterEntity;
import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.entity.dto.UpdateFilterRequestDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractDTO;
import com.aizuda.boot.modules.business.contract.mapper.ContractFieldMapper;
import com.aizuda.boot.modules.business.contract.service.EmployeeTableFilterService;
import com.alibaba.fastjson.JSON;


import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/contract/filter")
@Tag(name = "员工筛选字段配置")
@RequiredArgsConstructor
public class EmployeeTableFilterController {

    @Resource
    private EmployeeTableFilterService filterService;
    
    @Resource
    private ContractFieldMapper contractFieldMapper;

    @PostMapping("/update")
    @Operation(summary = "更新员工筛选字段配置")
    public SingleResponse updateFilters(@RequestBody UpdateFilterRequestDTO request) {
        filterService.updateFiltersByEmployeeId(request.getEmployeeId(), request.getFilters());
        return SingleResponse.success();
    }

    @GetMapping("/{employeeId}")
    @Operation(summary = "根据员工ID查询筛选字段配置")
    public SingleResponse<EmployeeTableFilterEntity> getFiltersByEmployeeId(@PathVariable Long employeeId) throws IllegalAccessException {
        EmployeeTableFilterEntity config = filterService.getByEmployeeId(employeeId);
        
        // 如果没有配置或者filters为空，创建默认配置
        if (config == null || config.getFilters() == null || config.getFilters().trim().isEmpty()) {
            // 创建新的配置记录，让数据库默认值生效
            EmployeeTableFilterEntity newConfig = new EmployeeTableFilterEntity();
            newConfig.setEmployeeId(employeeId);
            // 不设置filters字段，让数据库默认值生效
            filterService.save(newConfig);
            
            // 重新查询获取带有默认值的配置
            config = filterService.getByEmployeeId(employeeId);
            
            // 如果重新查询后仍然没有filters，返回空配置
            if (config == null || config.getFilters() == null || config.getFilters().trim().isEmpty()) {
                config = new EmployeeTableFilterEntity();
                config.setEmployeeId(employeeId);
                config.setFilters("[]"); // 设置空数组作为默认值
                config.setFields(new ArrayList<>());
                return SingleResponse.of(config);
            }
        }
        
        String filtersStr = config.getFilters();
        filtersStr = filtersStr.replace("[", "").replace("]", "");
        
        // 如果是空字符串，返回空字段列表
        if (filtersStr.trim().isEmpty()) {
            config.setFields(new ArrayList<>());
            return SingleResponse.of(config);
        }
        
        List<Integer> filters = Arrays.stream(filtersStr.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty()) // 过滤空字符串
                .map(Integer::valueOf)
                .collect(Collectors.toList());
                
        List<ContractDTO.ModuleDTO.FieldDTO> fieldByIds = contractFieldMapper.findFieldByIds(filters);
        // 设置字段选项
        fieldByIds.forEach(field -> {
            ContractFieldEntity fieldEntity = contractFieldMapper.selectById(field.getId());
            if (fieldEntity != null && fieldEntity.getFieldOptions() != null) {
                // 将字符串转换为 Map
                field.setFieldOptions(JSON.parseObject(fieldEntity.getFieldOptions()));
            }
        });
        config.setFields(fieldByIds);
        
        return SingleResponse.of(config);
    }
} 